package club.weiyuanstudio.android.app.message_station.ui.setting

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import club.weiyuanstudio.android.app.message_station.R

class SettingFragment : Fragment() {
    private val settingViewModel: SettingViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_setting, container, false)

        /* set save button */
        view.findViewById<Button>(R.id.button).setOnClickListener {
            val parentView = it.parent as View

            val deviceName =
                parentView.findViewById<TextView>(R.id.editTextDeviceName).text.toString()
            val apiToken =
                parentView.findViewById<TextView>(R.id.editTextApiToken).text.toString()

            settingViewModel.setSettingDataToPreferences(
                SettingViewModel.SettingData(
                    "",
                    deviceName,
                    apiToken
                )
            )

            Toast.makeText(context, "SAVED", Toast.LENGTH_SHORT).show()
        }

        /* bind view model to view */
        settingViewModel.settingData.observe(viewLifecycleOwner, {
            view.findViewById<EditText>(R.id.editTextUUID).setText(it.uuid)
            view.findViewById<EditText>(R.id.editTextDeviceName).setText(it.deviceName)
            view.findViewById<EditText>(R.id.editTextApiToken).setText(it.apiToken)
        })

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        settingViewModel.loadSettingDataFromPreferences()

        super.onViewCreated(view, savedInstanceState)
    }
}
